<?php
namespace x\my;
use x\my\Curl;

/**
 * 易宝收款宝类(utf-8)
 *
 * @author dev
 * @method fee 子商户费率设置
 * @method queryFee 子商户费率查询
 * @method reg 子商户注册
 * @method tradeLimit 子商户限额接口
 * @method queryTradeLimit 子商户限额查询接口
 * @method info 子商户信息查询
 * @method userBank 修改子商户银行卡信息
 * @method userFreeze 冻结或解冻子商户
 * @method userPhoto 补充子商户资质
 * @method userRisk 更改用户结算方式
 * @method thawTrade 订单解冻
 * @method usreAudit 用户审核
 * @method trade 收款（仅店主收款）
 * @method tradeNotice 收款回调处理
 * @method login 匿名登陆接口
 * @method Draw 出款接口
 * @method drawNotice 出款回调处理
 * @method queryUserPhoto 生成查看子商户资质的URL
 * @method userBalance 账户余额
 *        
 */
class Skb
{

    protected $config;

    protected $push;

    function __construct($domain = '')
    {
        // 田波 10013224741
        $this->config = array(
            'yeepayUrl' => 'https://skb.yeepay.com/skb-app/', // 易宝服务端站点
            'md5Key' => 'h8VV8k2337HgrHL9gBn8K2615KXa710vKd4IB27953nqq5PP0gnhVsQ0H900', // Md5密钥
            'parentId' => '10001674445', // 易宝大商户号
            'tradeNotifyUrl' => $domain . "webapp/yeepayskb/notice/", // 收款回调页面地址
            'tradeReturnUrl' => $domain . "webapp/yeepayskb/display/", // 收款跳转地址
            'drawNoticeUrl' => $domain . "webapp/async/yeepayskbtranfer/"
        ); // 出款回调页面地址
    }

    /**
     * 查询出款状态
     *
     * @param string $tradeNo
     *            出款流水号
     * @param number $isUrgent
     *            是否加急
     * @param string $customerNumber
     *            小商户编号
     * @param string $requestDateSectionBegin
     *            开始时间
     * @param string $requestDateSectionEnd
     *            结束时间
     * @param string $transferStatus
     *            出款状态
     * @return string[]|mixed
     */
    public function transferQuery($tradeNo = '', $isUrgent = 0, $customerNumber = '', $requestDateSectionBegin = '', $requestDateSectionEnd = '', $transferStatus = '')
    {
        $url = "transferQuery.action";
        $data = array(
            'customerNumber' => (string) $customerNumber,
            'externalNo' => (string) $tradeNo,
            'mainCustomerNumber' => (string) $this->config['parentId'],
            'pageNo' => '1',
            'requestDateSectionBegin' => (string) $requestDateSectionBegin,
            'requestDateSectionEnd' => (string) $requestDateSectionEnd,
            'transferStatus' => (string) $transferStatus,
            'transferWay' => (string) $isUrgent
        );
        
        $return = array(
            'code' => '0000',
            'message' => ''
        );
        
        $result = $this->yeepayData($url, $data);
        if ((string) $result['code'] != '')
            return $result;
        if ($result['hmac'] != $this->buld_sign($this->buld_pram(array(
            'code' => $result['code'],
            'message' => $result['message'],
            'totalRecords' => $result['totalRecords'],
            'transferRequests' => $result['transferRequests']
        )))) {
            $return['code'] = "9998";
            $return['msg'] = "服务端签名检验错误";
        }
        return $result;
    }

    /**
     * 查询子商户余额
     *
     * @param string $customernumber
     *            子商户编号
     * @param string $type
     *            1|日结通可用余额, 2|提现可用余额,3|账户余额
     */
    public function userBalance($customernumber = '', $type = 1)
    {
        $url = "customerBalanceQuery.action";
        $data = array(
            'mainCustomerNumber' => $this->config['parentId'],
            'customerNumber' => $customernumber,
            'balanceType' => (string) $type
        );
        
        $return = array(
            'code' => '0000',
            'message' => ''
        );
        
        $result = $this->yeepayData($url, $data);
        if ((string) $result['code'] != '')
            return $result;
        if ($result['hmac'] != $this->buld_sign($this->buld_pram(array(
            'code' => $result['code'],
            'message' => $result['message'],
            'mainCustomerNumber' => $this->config['parentId'],
            'customerNumber' => $result['customerNumber'],
            'balanceType' => $result['balanceType'],
            'balance' => $result['balance']
        )))) {
            $return['code'] = "9998";
            $return['msg'] = "服务端签名检验错误";
        }
        return $result;
    }

    /**
     * 生成查看子商户资质的URL
     *
     * @param string $customerNumber            
     * @param string $mobilePhone            
     * @return string
     */
    public function queryUserPhoto($customerNumber = "", $mobilePhone = '')
    {
        $url = "queryCustomerQualification.action";
        
        $data = array(
            'mainCustomerNumber' => $this->config['parentId']
        );
        
        if ($customerNumber != '')
            $data['customerNumber'] = $customerNumber;
        if ($mobilePhone != '')
            $data['mobilePhone'] = $mobilePhone;
        $data['hmac'] = $this->buld_sign($this->buld_pram($data));
        
        return $this->config['yeepayUrl'] . $url . "?" . $this->buld_pram($data, "key");
    }

    /**
     * 补充子商户资质
     *
     * @param string $customerNumber
     *            子商户编号
     * @param string $bankCardPhoto
     *            银行卡正面照
     * @param string $busiNessLicenSePhoto
     *            个体工商证正面照
     * @param string $idCardPhoto
     *            身份证正面照
     * @param string $idCardBackPhoto
     *            身份证背面照
     * @param string $personPhoto
     *            本人、身份证、银行照
     *            
     *            几个照片至少传一张
     */
    public function userPhoto($customerNumber = '', $bankCardPhoto = '', $busiNessLicenSePhoto = '', $idCardPhoto = '', $idCardBackPhoto = '', $personPhoto = '')
    {
        $url = "customerPictureUpdate.action";
        $data = array(
            'mainCustomerNumber' => $this->config['parentId'],
            'customerNumber' => $customerNumber
        );
        
        $data['hmac'] = $this->buld_sign($this->buld_pram($data));
        
        $photos = array(
            'bankCardPhoto' => $bankCardPhoto,
            'BusinessLicensePhoto' => $busiNessLicenSePhoto,
            'idCardPhoto' => $idCardPhoto,
            'idCardBackPhoto' => $idCardBackPhoto,
            'personPhoto' => $personPhoto
        );
        
        foreach ($photos as $key => $val) {
            if ($bankCardPhoto != '' && is_file($val)) {
                $data[$key] = new \CURLFile($val, 'image/jpeg', "photo.jpg");
            }
        }
        
        $return = array(
            'code' => '0000',
            'message' => ''
        );
        
        $result = $this->yeepayData($url, $data);
        if ((string) $result['code'] != '')
            return $result;
        if ($result['hmac'] != $this->buld_sign($this->buld_pram(array(
            'code' => $result['code'],
            'message' => $result['message'],
            'status' => $result['status']
        )))) {
            $return['code'] = "9998";
            $return['msg'] = "服务端签名检验错误";
        }
        return $result;
    }

    /**
     * 出款接口
     *
     * @param string $customerNumber
     *            子商户编号
     * @param number $amount
     *            出款金额
     * @param string $externalNo
     *            出款流水号
     * @param string $transferWay
     *            出款方式:1|日结通,2|委托结算
     * @return array
     */
    public function Draw($customerNumber = '', $amount = 0, $externalNo = "", $transferWay = '2', $noticeurl = false)
    {
        $url = "withDrawApi.action";
        
        $data = array(
            'amount' => (string) $amount,
            'customerNumber' => (string) $customerNumber,
            'externalNo' => $externalNo,
            'mainCustomerNumber' => $this->config['parentId'],
            'transferWay' => (string) $transferWay,
            'callBackUrl' => $noticeurl === false ? $this->config['drawNoticeUrl'] : $noticeurl
        );
        
        $return = array(
            'code' => '0000',
            'message' => ''
        );
        
        $result = $this->yeepayData($url, $data);
        
        if ((string) $result['code'] != '')
            return $result;
        if ($result['hmac'] != $this->buld_sign($this->buld_pram(array(
            'amount' => $result['amount'],
            'code' => $result['code'],
            'customerNumber' => $result['customerNumber'],
            'externalNo' => $result['externalNo'],
            'mainCustomerNumber' => $this->config['parentId'],
            'message' => $result['message'],
            'serialNo' => $result['serialNo'],
            'transferWay' => (string) $result['transferWay']
        )))) {
            $return['code'] = "9998";
            $return['msg'] = "服务端签名检验错误";
        }
        return $result;
    }

    /**
     *
     * @param string $customerNumber
     *            子商户编号
     * @param string $target
     *            登封成功后跳转的页面:
     *            all或默认|链至【掌上收银台】,有底部导航栏,
     *            handCaher|链至【掌上收银台】,没有底部导航栏,
     *            myAccount:链至【我的账户】,没有底 部导航栏
     * @return string 子商户的URL地址
     */
    public function login($customerNumber = '', $target = "all")
    {
        $url = $this->config['yeepayUrl'] . "loginFromApp.action?";
        $data = array(
            "mainCustomerNumber" => $this->config['parentId'],
            'customerNumber' => $customerNumber
        );
        
        $data['hmac'] = $this->buld_sign($this->buld_pram($data));
        $data['target'] = $target;
        return $url . $this->buld_pram($data, "key");
    }

    /**
     * 提现异步通知
     *
     * @return string
     */
    public function drawNotice()
    {
        $data = array(
            'mainCustomerNumber' => (string) $this->config['parentId'],
            'customerNumber' => (string) $this->g('customerNumber'), // 子商户编码
            'externalNo' => (string) $this->g('externalNo'), // 大商户的出款订单号
            'serialNo' => (string) $this->g('serialNo'), // 易宝唯一的交易流水号
            'transferStatus' => (string) $this->g('transferStatus'), // 出款状态 已接受 RECEIVED, 处理中 PROCESSING, 打款成功 SUCCESSED, 打款失败 FAILED, 已退款 REFUNED, 已撤销 CANCELLED
            'requestTime' => (string) $this->g('requestTime'), // 请求时间 时间格式:yyyy-mm-dd hh:mm:ss
            'handleTime' => (string) $this->g('handleTime'), // 处理时间 时间格式:yyyy-mm-dd hh:mm:ss
            'transferWay' => (string) $this->g('transferWay'), // 出款类型 1| T+0, 2 | T+1 ,3 |自动T+1结算
            'receiver' => (string) $this->g('receiver'), // 收款人
            'receiverBankCardNo' => (string) $this->g('receiverBankCardNo'), // 收款卡号
            'receiverBank' => (string) $this->g('receiverBank'), // 收款银行
            'amount' => (string) $this->g('amount'), // 金额
            'fee' => (string) $this->g('fee'), // 手续费
            'basicFee' => (string) $this->g('basicFee'), // 基本手续费
            'exTargetFee' => (string) $this->g('exTargetFee'), // 额外手续费
            'actualAmount' => (string) $this->g('actualAmount'), // 实收金额
            'failReason' => (string) $this->g('failReason')
        ); // 失败原因
        
        $returnData = array();
        $info = "签名检验失败";
        $code = "4103";
        if ($this->g("hmac") == $this->buld_sign($this->buld_pram($data))) {
            $code = "200";
            $info = "SUCCESS";
            $returnData = array(
                'data' => array(
                    'externalNo' => $data['externalNo'],
                    'transferStatus' => $data['transferStatus'],
                    'customerNumber' => $data['customerNumber'],
                    'bizno' => '',
                    $data['batchNo'],
                    'amount' => $data['amount'],
                    'message' => $this->g('message'),
                    'serialNo' => $data['serialNo']
                )
            );
            // 开始业务处理
        }
        
        return msg($code, $info, $returnData);
    }

    /**
     * 收款回调处理
     *
     * @return string SUCCESS|成功，其它|失败，直接返给易宝即可
     */
    public function tradeNotice()
    {
        $data = array(
            'code' => (string) $this->g("code"), // 支付返回码
            'message' => (string) $this->g('message'), // 支付消息码具体信息
            'requestId' => (string) $this->g('requestId'), // 大商户请求的订单号
            'customerNumber' => (string) $this->g('customerNumber'), // 子商户编码
            'externalld' => (string) $this->g('externalld'), // 易宝交易流水号
            'createTime' => (string) $this->g('createTime'), // 请求时间
            'payTime' => (string) $this->g('payTime'), // 支付时间
            'amount' => (string) $this->g('amount'), // 订单金额
            'fee' => (string) $this->g('fee'), // 扣取的大商户手续费
            'status' => (string) $this->g('status'), // 订单状态： FAIL|失败、未支付 SUCCESS|成功 FORZEN|冻结 THAWED|解冻
            'busiType' => (string) $this->g('busiType'), // 业务类型：COMMON 普通交易 ASSURE 担保交易
            'bankCode' => (string) $this->g('bankCode'), // 银行编码
            'payerName' => (string) $this->g('payerName'), // 持卡人姓名
            'payerPhone' => (string) $this->g('payerPhone'), // 持卡人手机号
            'lastNo' => (string) $this->g('lastNo'), // 银行卡后四位
            'src' => (string) $this->g('src')
        ); // D - 卡号收款 B - 店主收款 S - 短信收款 T - 二维码收款 W - 微信支付
        
        $this->_log($_REQUEST, "tradeNotice");
        
        $code = "4103";
        $retrunData = [];
        $info = "SUCCESS";
        
        if ($this->g("hmac") == $this->buld_sign($this->buld_pram($data))) {
            $code = "200";
            // 开始业务处理
            $retrunData = [
                'customerNumber' => $data['customerNumber'],
                'tradeNo' => $data['requestId'],
                'amount' => $data['amount'],
                'fee' => $data['fee'],
                'status' => $data['status'],
                'bankCode' => $data['bankCode'],
                'lastNo' => $data['lastNo'],
                'payerPhone' => $data['payerPhone'],
                'payerName' => $data['payerName']
            ];
        }
        return [
            'code' => $code,
            'data' => $retrunData
        ];
    }

    /**
     * 收款（仅店主收款）
     *
     * @param string $customerNumber            
     * @param number $amount     订单金额: 元
     * @param string $tradeNo     
     * @param string $payBankNo            
     * @param string $mcc            
     */
    public function trade($customerNumber = '', $amount = 0, $tradeNo = '', $payBankNo = '', $mcc = "5311", $noticeUrl = false, $tradeReturnUrl = false)
    {
        $url = "receiveApi.action";
        $data = array(
            'source' => 'B', // 支付方式 D - 卡号收款B - 店主收款S - 短信收款T - 二维码收款 W - 微信支付
            'mainCustomerNumber' => (string) $this->config['parentId'],
            'customerNumber' => (string) $customerNumber,
            'amount' => (string) number_format($amount, 2, '.', ''),
            'mcc' => (string) $mcc,
            'requestId' => (string) $tradeNo,
            'callBackUrl' => $noticeUrl === false ? $this->config['tradeNotifyUrl'] : $noticeUrl, // 回调页面地址
            'webCallBackUrl' => $tradeReturnUrl === false ? $this->config['tradeReturnUrl'] : $tradeReturnUrl
        ); // 支付后跳转地址
        
        if ($payBankNo != '')
            $data['payerBankAccountNo'] = $payBankNo; // 支付银行卡号
        
        $result = $this->yeepayData($url, $data);
        if ($result['code'] == '0000') {
            $result['url'] = $this->decrypt($result['url']);
        }
        
        return $result;
    }

    /**
     * 审核用户
     *
     * @param string $customerNumber
     *            子商户编号
     * @param string $status
     *            审核状态 SUCCESS|通过,FAILED|拒绝
     * @param string $reason
     *            如果审核状态为拒绝，此处为拒绝原因
     */
    public function usreAudit($customerNumber = '', $status = "SUCCESS", $reason = '')
    {
        $url = "auditMerchant.action";
        $data = array(
            'customerNumber' => $customerNumber,
            'mainCustomerNumber' => $this->config['parentId'],
            'status' => $status,
            'reason' => $reason
        );
        if ($reason == '')
            unset($data['reason']);
        
        return $this->yeepayData($url, $data);
    }

    /**
     * 订单解冻
     *
     * @param string $customerNumber
     *            子商户编号
     * @param string $tradeNo
     *            交易订单号
     */
    public function thawTrade($customerNumber = "", $tradeNo = "")
    {
        $url = "thawTrade.action";
        $data = array(
            'customerNumber' => $customerNumber,
            'mainCustomerNumber' => $this->config['parentId'],
            'requestId' => $tradeNo
        );
        
        $return = array(
            'code' => '0000',
            'message' => ''
        );
        
        $result = $this->yeepayData($url, $data);
        if ((string) $result['code'] != '')
            return $result;
        if ($result['hmac'] != $this->buld_sign($this->buld_pram(array(
            'code' => $result['code'],
            'requestId' => $result['requestId'],
            'amount' => $result['amount']
        )))) {
            $return['code'] = "9998";
            $return['msg'] = "易宝签名检验错误";
        }
        return $result;
    }

    /**
     * 更改用户结算方式
     *
     * @param string $customerNumber
     *            子商户编号
     * @param string $riskReserveDay
     *            客户结算方式:0|T0结算,1|T1结算
     * @param string $bankName
     *            是否自动提款给客户 Y|需客户手工操作，N|T1自助结算给用户
     */
    public function userRisk($customerNumber = "", $riskReserveDay = "", $manualSettle = "Y")
    {
        $url = "customerInforUpdate.action";
        $data = array(
            'mainCustomerNumber' => $this->config['parentId'],
            'customerNumber' => $customerNumber,
            'riskReserveDay' => (string) $riskReserveDay,
            'manualSettle' => (string) $manualSettle
        );
        $data['hmac'] = $this->buld_sign($this->buld_pram($data));
        $data['modifyType'] = '3';
        return $this->yeepayData($url, $data);
    }

    /**
     * 冻结用户
     *
     * @param string $customerNumber
     *            子商户编号
     * @param number $type
     *            冻结或解冻 0|冻结,1|解冻
     * @param string $freezeDays
     *            冻结天数，如果为冻结，此处为冻结天数
     */
    public function userFreeze($customerNumber = "", $type = 0, $freezeDays = '')
    {
        $url = "customerInforUpdate.action";
        $data = array(
            'mainCustomerNumber' => $this->config['parentId'],
            'customerNumber' => $customerNumber,
            'whiteList' => (string) $type,
            'freezeDays' => (string) $freezeDays
        );
        $data['hmac'] = $this->buld_sign($this->buld_pram($data));
        $data['modifyType'] = '1';
        return $this->yeepayData($url, $data);
    }

    /**
     * 更改用户银行卡信息
     *
     * @param string $customerNumber
     *            子商户编号
     * @param string $bankCardNumber
     *            银行卡卡号
     * @param string $bankName
     *            开户行 【工商银行、农业银行、招商银 行、建设银行、交通银行、中信银行、光大银行、北京银行、深圳发展银行 、中国银行、兴业银行、民生银行】
     */
    public function userBank($customerNumber = "", $bankCardNumber = "", $bankName = "")
    {
        $url = "customerInforUpdate.action";
        $data = array(
            'mainCustomerNumber' => $this->config['parentId'],
            'customerNumber' => $customerNumber,
            'bankCardNumber' => (string) $bankCardNumber,
            'bankName' => (string) $bankName
        );
        $data['hmac'] = $this->buld_sign($this->buld_pram($data));
        $data['modifyType'] = '2';
        return $this->yeepayData($url, $data);
    }

    /**
     * 修改商户为T1自动出款
     *
     * @param string $customerNumber            
     */
    public function userAutoT1($customerNumber = '')
    {
        $url = "customerInforUpdate.action";
        $data = array(
            'mainCustomerNumber' => $this->config['parentId'],
            'customerNumber' => $customerNumber,
            'riskReserveDay' => (string) 0,
            'manualSettle' => (string) 'N'
        );
        $data['hmac'] = $this->buld_sign($this->buld_pram($data));
        $data['modifyType'] = '3';
        return $this->yeepayData($url, $data);
    }

    /**
     * 子商户信息查询
     *
     * @param string $mobilePhone
     *            子商户手机号码
     */
    public function info($mobilePhone = "")
    {
        $url = "customerInforQuery.action";
        $data = array(
            'mainCustomerNumber' => $this->config['parentId'],
            'mobilePhone' => $mobilePhone
        );
        return $this->yeepayData($url, $data);
    }

    /**
     * 子商户限额查询接口
     *
     * @param string $customerNumber
     *            子商户编号
     * @param string $bankCardType
     *            银行卡类型:DEBIT 借记卡 CREDIT 信用卡
     * @param number $tradeLimitConfigKey
     *            限额类型： 1店主 2非店主 3子商户 4非店主卡
     * @param string $bankCardNo
     *            银行卡号
     */
    public function queryTradeLimit($customerNumber = '', $bankCardType = "DEBIT", $tradeLimitConfigKey = 1, $bankCardNo = '')
    {
        $url = "tradeLimitQuery.action";
        $data = array(
            'customerNumber' => (string) $customerNumber,
            'mainCustomerNumber' => $this->config['parentId'],
            'bankCardType' => (string) $bankCardType,
            'bankCardNo' => $bankCardNo,
            'tradeLimitConfigKey' => (string) $tradeLimitConfigKey
        );
        if ($data['bankCardNo'] == '')
            unset($data['bankCardNo']);
        return $this->yeepayData($url, $data);
    }

    /**
     * 子商户限额设置接口
     *
     * @param number $customerNumber
     *            子商户编号
     * @param number $tradeLimitConfigKey
     *            限额类型： 1店主 2非店主 3子商户 4非店主卡
     * @param string $bankCardType
     *            银行卡类型:DEBIT 借记卡 CREDIT 信用卡
     * @param number $singleAmount
     *            单笔限额:正整数,且不大于默认值
     * @param number $dayAmount
     *            日限额:正整数,且不大于默认值
     * @param number $monthAmount
     *            月限额:正整数,且不大于默认值
     * @param number $dayCount
     *            日累计次数:正整数
     * @param number $monthCount
     *            月累计次数
     * @param string $bankCardNo
     *            银行卡号
     */
    public function tradeLimit($customerNumber = 0, $tradeLimitConfigKey = 1, $bankCardType = "DEBIT", $singleAmount = 0, $dayAmount = 0, $monthAmount = 0, $dayCount = 0, $monthCount = 0, $bankCardNo = '')
    {
        $url = "tradeLimitSet.action";
        $data = array(
            'customerNumber' => (string) $customerNumber,
            'mainCustomerNumber' => $this->config['parentId'],
            'bankCardType' => (string) $bankCardType,
            'bankCardNo' => $bankCardNo,
            'tradeLimitConfigKey' => (string) $tradeLimitConfigKey,
            'singleAmount' => (string) $singleAmount,
            'dayAmount' => (string) $dayAmount,
            'monthAmount' => (string) $monthAmount,
            'dayCount' => (string) $dayCount,
            'monthCount' => (string) $monthCount
        );
        if ($data['bankCardNo'] == '')
            unset($data['bankCardNo']);
        return $this->yeepayData($url, $data);
    }

    /**
     * 费率设置
     *
     * @param string $customerNumber            
     * @param number $ype            
     * @param number $rate            
     */
    public function fee($customerNumber = '', $type = 1, $rate = 1)
    {
        $url = "feeSetApi.action";
        $data = array(
            'customerNumber' => $customerNumber, // 子商户编号
            'mainCustomerNumber' => $this->config['parentId'],
            'productType' => (string) $type, // 整数类型, 1.交易 2.提现 3.日结通基本 4.日结通额外 5.日结通非工作日 6.微信
            'rate' => (string) $rate
        );
        
        return $this->yeepayData($url, $data);
    }

    /**
     * 费率查询
     *
     * @param string $customerNumber            
     * @param number $type            
     */
    public function queryFee($customerNumber = '', $type = 1)
    {
        $url = "queryFeeSetApi.action";
        $data = array(
            'customerNumber' => $customerNumber, // 子商户编号
            'mainCustomerNumber' => $this->config['parentId'],
            'productType' => (string) $type
        ); // 整数类型, 1.交易 2.提现 3.日结通基 本 4.日结通额外 5.日结通非工作日 6.微信
        
        return $this->yeepayData($url, $data);
    }

    /**
     * 子商户注册
     *
     * @param string $TradeNo
     *            流水号
     * @param string $phone
     *            绑定手机号码
     * @param string $name
     *            姓名
     * @param string $idNo
     *            身份证号码
     * @param string $bankNo
     *            银行卡号
     * @param string $bankName
     *            开户银行
     * @param string $areaCode
     *            地区码
     * @param string $BankCardPhoto
     *            银行卡正面照片
     * @param string $idCardPhoto
     *            身份证正面照片
     * @param string $idCardBackPhoto
     *            身份证背面照片
     * @param string $PersonPhoto
     *            人，证，银行卡合照
     */
    public function reg($TradeNo = '', $phone = '', $name = '', $idNo = '', $bankNo = '', $bankName = '', $areaCode = '', $BankCardPhoto = '', $idCardPhoto = '', $idCardBackPhoto = '', $PersonPhoto = '', $debug = '')
    {
        $url = "register.action";
        
        $data = array(
            'mainCustomerNumber' => (string) $this->config['parentId'],
            'requestId' => (string) $TradeNo, // 注册流水号
            'customerType' => 'PERSON', // 个人|PERSON , ENTERPRISE|企业 , INDIVIDUAL|个体工商户
            'bindMobile' => (string) $phone, // 绑定的手机号
            'signedName' => (string) $name, // 商户签约名： 在注册商户类型为个人用户时,保证 签约名和开户名一样; 在注册商户类型为企业、个体工商户 时,签约名传企业名称全称
            'linkMan' => (string) $name, // 推荐人姓名
            'idCard' => (string) $idNo, // 商户法人身份证号,同一个身份证号，只能在一个大商户下注册一个账号
            'legalPerson' => (string) $name, // 商户的法人姓名
            'minSettleAmount' => '20', // 起结金额
            'riskReserveDay' => '0', // 0|T0出款,N|TN出款
            'bankAccountNumber' => (string) $bankNo,
            'bankName' => (string) $bankName, // 工商银行、农业银行、招商银行、建设银行、交通银行、中信银行、光大银行、北京银行、深圳发展银行 、中国银行、兴业银行、民生银行
            'accountName' => (string) $name, // 开户名
            'areaCode' => (string) $areaCode, // 商户所在地区,请根据【银联 32 域码 表 0317.xls-来自易宝】,填写编码
            'certFee' => '0', // 认证费用
            'manualSettle' => 'N', // N否是自助结算 N - 隔天自动打 款;Y - 不会自动打款
            'BankCardPhoto' => new \CURLFile($BankCardPhoto, 'image/jpeg', 'BankCardPhoto.jpg'), // 银行卡正面照
            'idCardPhoto' => new \CURLFile($idCardPhoto, 'image/jpeg', 'idCardPhoto.jpg'), // 身份证正面照
            'idCardBackPhoto' => new \CURLFile($idCardBackPhoto, 'image/jpeg', 'idCardBackPhoto.jpg'), // 身份证背面照
            'PersonPhoto' => new \CURLFile($PersonPhoto, 'image/jpeg', 'PersonPhoto.jpg')
        ); // 银行卡与身份证及本人上半身合照
        //t($data);

        return $this->yeepayData($url, $data, $debug);
    }

    /**
     * 获取易宝数据
     *
     * @param string $url            
     * @param array $data            
     */
    private function yeepayData($url = "", $data = array(), $debug = '')
    {
        if (! isset($data['hmac']))
            $data['hmac'] = $this->buld_sign($this->buld_pram($data));
        
        $url = $this->config['yeepayUrl'] . $url;

        // $ch = curl_init($url);
        // curl_setopt($ch, CURLOPT_POST,1);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        // $result = curl_exec($ch);
        // curl_close($ch);

        $result = Curl::post($url,$data);
        
        if ($debug != '')
            t($result);
        
        $result = json_decode($result, true);
        return $result ? $result : array(
            'code' => '9997',
            'message' => '服务端数据请求错误:'.$result['message']
        );
    }

    /**
     * 参数处理
     *
     * @param array $data            
     */
    private function buld_pram($data = array(), $method = "")
    {
        $str = '';
        if (count($data) < 1)
            return $str;
        foreach ($data as $key => $val) {
            if (gettype($val) != 'string')
                continue;
            if ($method != '') {
                if ($str != '')
                    $str .= "&";
                $str .= "$key=$val";
            } else {
                $str .= $val;
            }
        }
        return $str;
    }

    /**
     * 生成签名
     *
     * @param string $str            
     */
    private function buld_sign($str = '')
    {
        return $this->HmacMd5($str, $this->config['md5Key']);
    }

    /**
     * HmacMd5计算
     *
     * @param string $data            
     * @param string $key            
     */
    private function HmacMd5($data = "", $key = "")
    {
        $b = 64; // byte length for md5
        if (strlen($key) > $b) {
            $key = pack("H*", md5($key));
        }
        $key = str_pad($key, $b, chr(0x00));
        $ipad = str_pad('', $b, chr(0x36));
        $opad = str_pad('', $b, chr(0x5c));
        $k_ipad = $key ^ $ipad;
        $k_opad = $key ^ $opad;
        
        return md5($k_opad . pack("H*", md5($k_ipad . $data)));
    }

    /**
     * 加密
     *
     * @param string $input
     *            明文
     */
    private function encrypt($input = "")
    {
        $key = $this->config['md5Key'];
        if (strlen($key) > 16)
            $key = substr($key, 0, 16);
        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $input = $this->pkcs5_pad($input, $size);
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, $key, $iv);
        $data = mcrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        $data = $this->strToHex($data);
        return $data;
    }

    private function pkcs5_pad($text, $blocksize)
    {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    /**
     * 字符串转16进制
     *
     * @param string $string            
     * @return string
     */
    function strToHex($string = "") // 字符串转十六进制
    {
        $hex = "";
        for ($i = 0; $i < strlen($string); $i ++)
            $hex .= dechex(ord($string[$i]));
        $hex = strtoupper($hex);
        return $hex;
    }

    /**
     * 十六进行转化成字符串
     *
     * @param string $hex            
     * @return string
     */
    function hexToStr($hex = "") // 十六进制转字符串
    {
        $string = "";
        for ($i = 0; $i < strlen($hex) - 1; $i += 2)
            $string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
        return $string;
    }

    /**
     * 解密
     *
     * @param string $sStr
     *            密文
     */
    private function decrypt($sStr = "")
    {
        $sKey = $this->config['md5Key'];
        if (strlen($sKey) > 16)
            $sKey = substr($sKey, 0, 16);
        $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $sKey, $this->hexToStr($sStr), MCRYPT_MODE_ECB);
        
        $dec_s = strlen($decrypted);
        $padding = ord($decrypted[$dec_s - 1]);
        $decrypted = substr($decrypted, 0, - $padding);
        return urldecode($decrypted);
    }

    private function _log($data = [], $t = 'notice')
    {
        if (count($data) == 0)
            return;
        file_put_contents('./skb_' . date("Ymd") . '.txt', "---------------$t------------\r\n" . http_build_query($data) . "\r\n", FILE_APPEND);
    }

    /**
     * 无警告信息获取用户提交的值
     *
     * @param string $key
     *            参数名：数字、字母、下划线
     * @param string $method
     *            all,post与get
     * @param string $default
     *            如为空的默认值
     * @return string
     */
    function g($key = "", $method = 'all', $default = '')
    {
        if ($key == '') {
            return $default;
        }
        
        switch (strtolower($method)) {
            case 'post':
                $url = $_POST;
                break;
            case 'get':
                $url = $_GET;
                break;
            default:
                $url = $_REQUEST;
                break;
        }
        return (isset($url[$key])) ? $url[$key] : $default;
    }
}